<template>
  <div class="project-form-manager-page">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item @click="goBack" class="breadcrumb-link">
          项目管理
        </el-breadcrumb-item>
        <el-breadcrumb-item v-if="project">
          {{ project.name }}
        </el-breadcrumb-item>
      </el-breadcrumb>

      <div class="project-actions">
            <el-badge :value="frontMatterIds.length" :hidden="frontMatterIds.length===0" type="primary">
              <el-button 
                type="default"
                size="small"
                @click="showFrontMatterDialog = true"
              >前置页管理</el-button>
            </el-badge>
            <el-button 
              type="success" 
              :icon="exporting ? Loading : DocumentCopy" 
              size="small" 
              @click="exportWord"
              :loading="exporting"
              :disabled="exporting"
            >
              {{ exporting ? '导出中...' : '导出Word' }}
            </el-button>
            <el-button type="primary" size="small" @click="showPublish = true">发布版本</el-button>
            <el-button type="default" size="small" @click="goVersionManager">版本管理</el-button>
            <el-button type="default" size="small" @click="goVersionCompare">版本对比</el-button>
      </div>
      
      <!-- 项目信息卡片 -->
      <!-- <div class="project-card" v-if="project">
        <div class="project-header">
          <h2 class="project-name">{{ project.name }}</h2>
          
        </div>
        <div class="project-meta">
          <div class="meta-item">
            <span class="meta-label">协议编号：</span>
            <span class="meta-value">{{ project.protocolNumber }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">状态：</span>
            <el-tag :type="getStatusType(project.status)" size="small">
              {{ getStatusText(project.status) }}
            </el-tag>
          </div>
          <div class="meta-item">
            <span class="meta-label">版本：</span>
            <span class="meta-value">v{{ project.version }}</span>
          </div>
        </div>
      </div> -->
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-content">
        <el-icon class="loading-icon" size="48">
          <Loading />
        </el-icon>
        <p class="loading-text">正在加载项目信息...</p>
      </div>
    </div>

    <!-- 主要内容 -->
    <div v-else-if="project" class="page-content">

     <el-button :type="activeTab === 'forms' ? 'primary' : 'default'"  @click="activeTab = 'forms'">表单</el-button>
     <el-button :type="activeTab === 'sections' ? 'primary' : 'default'"  @click="activeTab = 'sections'">访视</el-button>
     <SectionList ref="sectionListRef" v-if="activeTab === 'sections'" />
     <FormList ref="formListRef" v-if="activeTab === 'forms'" />
      <!-- Tab 管理区域 -->
      
    </div>

    <!-- 项目不存在 -->
    <div v-else class="error-container">
      <el-result
        icon="warning"
        title="项目不存在"
        sub-title="请检查项目ID是否正确，或联系管理员"
      >
        <template #extra>
          <el-button type="primary" @click="goBack" size="large">
            返回项目列表
          </el-button>
        </template>
      </el-result>
    </div>
  </div>

  <!-- 前置页管理对话框 -->
  <el-dialog
    v-model="showFrontMatterDialog"
    title="前置页管理"
    width="840px"
    destroy-on-close
  >
    <FrontMatterManager
      v-if="project"
      :project-id="project._id || project.id"
      v-model="frontMatterList"
      @close="showFrontMatterDialog = false"
      @confirm="onFrontMatterConfirm"
    />
  </el-dialog>
  
  <!-- 发布版本对话框（快捷入口） -->
  <el-dialog v-model="showPublish" title="发布版本" width="520px" destroy-on-close>
    <el-form :model="publishForm" label-width="90px">
      <el-form-item label="版本号">
        <el-input v-model="publishForm.versionTag" placeholder="例如：V1.0" maxlength="20" />
      </el-form-item>
      <el-form-item label="发布说明">
        <el-input v-model="publishForm.description" type="textarea" :rows="3" maxlength="500" show-word-limit />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showPublish = false">取消</el-button>
      <el-button type="primary" :disabled="!canQuickPublish" :loading="publishing" @click="quickPublish">发布</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  ArrowLeft, 
  DocumentCopy, 
  Setting, 
  Loading, 
  Document, 
  EditPen
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import SectionList from '@/views/SectionList.vue'
import FormList from '@/views/FormList.vue'
import { useProjectStore } from '@/stores/project'
import { generateDocx, api } from '@/utils/api'
import FrontMatterManager from '@/components/modal/FrontMatterManager.vue'

const route = useRoute()
const router = useRouter()
const projectStore = useProjectStore()

const activeTab = ref('forms')
const loading = ref(true)
const project = ref(null)
const exporting = ref(false)
const showFrontMatterDialog = ref(false)
const showPublish = ref(false)
const publishing = ref(false)
const publishForm = ref({ versionTag: '', description: '' })
const canQuickPublish = computed(() => !!publishForm.value.versionTag && !!publishForm.value.description)
const frontMatterList = ref([])
const frontMatterIds = computed(() => (frontMatterList.value || []).map(i => i.formId))

// 子组件引用
const sectionListRef = ref(null)
const formListRef = ref(null)

// 获取项目信息
const fetchProject = async () => {
  try {
    loading.value = true
    const projectId = route.params.projectId
    
    console.log('尝试获取项目ID:', projectId)
    
    if (!projectId || projectId === 'undefined' || projectId === 'null') {
      ElMessage.error('项目ID无效')
      goBack()
      return
    }
    
    const projectData = await projectStore.fetchProject(projectId)
    if (!projectData) {
      ElMessage.error('项目不存在或已被删除')
      project.value = null
      return
    }
    
    project.value = projectData
    console.log('成功获取项目信息:', projectData.name)
  } catch (error) {
    console.error('获取项目信息失败:', error)
    
    // 根据错误类型给出不同提示
    if (error.response?.status === 404) {
      ElMessage.error('项目不存在')
    } else if (error.response?.status === 403) {
      ElMessage.error('没有访问该项目的权限')
    } else {
      ElMessage.error('获取项目信息失败')
    }
    
    project.value = null
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.push('/projects')
}

const goVersionManager = () => {
  router.push(`/projects/${route.params.projectId}/versions`)
}
const goVersionCompare = () => {
  router.push({ path: `/projects/${route.params.projectId}/versions/compare` })
}

// 快捷发布版本（无需进入版本管理页）
const quickPublish = async () => {
  if (!project.value) return
  if (!canQuickPublish.value) return
  publishing.value = true
  try {
    await api.versions.publish(project.value._id || project.value.id, {
      versionTag: publishForm.value.versionTag.trim(),
      description: publishForm.value.description.trim()
    })
    showPublish.value = false
    publishForm.value = { versionTag: '', description: '' }
    ElMessage.success('发布成功')
  } catch (e) {
    ElMessage.error(e.message || '发布失败')
  } finally {
    publishing.value = false
  }
}

// 状态显示
const getStatusType = (status) => {
  const map = {
    active: 'success',
    completed: 'info',
    paused: 'warning'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    active: '进行中',
    completed: '已完成',
    paused: '已暂停'
  }
  return map[status] || status
}

const exportWord = async () => {
  if (!project.value) {
    ElMessage.error('项目信息不存在，无法导出')
    return
  }

  try {
    // 确认导出
    await ElMessageBox.confirm(
      `确定要导出项目 "${project.value.name}" 的Word文档吗？`,
      '确认导出',
      {
        confirmButtonText: '确定导出',
        cancelButtonText: '取消',
        type: 'info',
        center: true
      }
    )

    exporting.value = true
    
    // 获取完整的项目配置数据
    const projectConfig = await projectStore.fetchProjectConfig(project.value._id)
    
    if (!projectConfig) {
      throw new Error('获取项目配置失败')
    }

    // 检查项目是否有配置的章节
    if (!projectConfig.configSections || projectConfig.configSections.length === 0) {
      ElMessage.warning({
        message: '项目尚未配置任何章节，将导出空白文档',
        duration: 3000
      })
    }

    // 调用导出函数
    await generateDocx(projectConfig)
    
    ElMessage.success({
      message: 'Word文档导出成功！',
      duration: 3000
    })
    
  } catch (error) {
    // 用户取消操作
    if (error === 'cancel') {
      ElMessage.info('已取消导出')
      return
    }
    
    console.error('导出Word失败:', error)
    ElMessage.error({
      message: `导出失败：${error.message || '未知错误'}`,
      duration: 5000
    })
  } finally {
    exporting.value = false
  }
}

// 打开前置页管理前先加载后端数据
watch(showFrontMatterDialog, async (val) => {
  if (val && project.value) {
    const fm = await projectStore.fetchFrontMatter(project.value._id || project.value.id)
    frontMatterList.value = fm
  }
})

// 前置页确认回调：保存到后端
const onFrontMatterConfirm = async ({ frontMatter }) => {
  try {
    await projectStore.saveFrontMatter(project.value._id || project.value.id, frontMatter)
    frontMatterList.value = frontMatter
    showFrontMatterDialog.value = false
    ElMessage.success('前置页已保存')
  } catch (e) {
    ElMessage.error('保存前置页失败')
  }
}

// 监听 tab 切换，重新获取数据
watch(activeTab, async (newTab) => {
  await nextTick()
  
  if (newTab === 'sections' && sectionListRef.value) {
    // 调用访视管理的数据获取方法
    if (typeof sectionListRef.value.getSections === 'function') {
      sectionListRef.value.getSections()
    }
  } else if (newTab === 'forms' && formListRef.value) {
    // 设置 projectId 并调用表单管理的数据获取方法
    if (typeof formListRef.value.getForms === 'function') {
      formListRef.value.queryParams.projectId = route.params.projectId;
      formListRef.value.getForms()
    }
  }
})

// 页面初始化
onMounted(() => {
  fetchProject()
})
</script>

<style scoped>
.project-form-manager-page {
  background: #ffffff;
}

.breadcrumb-container {
  padding: 16px 10px;
  background: #ffffff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.breadcrumb-link {
  cursor: pointer;
  color: #409eff;
}

.breadcrumb-link:hover {
  opacity: 0.8;
}

.project-card {
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  margin-top: 16px;
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.project-name {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.project-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.project-actions .el-button {
  min-width: 100px;
}

.project-actions .el-button.is-loading {
  pointer-events: none;
}

.project-meta {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.meta-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.meta-value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60vh;
}

.loading-content {
  text-align: center;
}

.loading-icon {
  color: #409eff;
  animation: pulse 2s infinite;
}

.loading-text {
  margin-top: 16px;
  color: #666;
  font-size: 16px;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.page-content {
  padding: 10px;
}



.manager-container {
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  overflow: hidden;
}

.manager-tabs {
  border: none;
  box-shadow: none;
}

:deep(.el-tabs__header) {
  margin: 0;
  background: #ffffff;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0 24px;
}

:deep(.el-tabs__item) {
  padding: 16px 24px;
  font-weight: 500;
  border: none;
  margin-right: 8px;
  border-radius: 8px 8px 0 0;
  transition: all 0.3s ease;
}

:deep(.el-tabs__item:hover) {
  background: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

:deep(.el-tabs__item.is-active) {
  background: white;
  color: #409eff;
  border-bottom: 2px solid #409eff;
}

:deep(.el-tabs__content) {
  padding: 0;
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
}

.tab-badge {
  margin-left: 4px;
}

.tab-content {
  padding: 32px;
  min-height: 600px;
}

.content-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.content-header h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.content-description {
  margin: 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60vh;
}

:deep(.el-result) {
  background: white;
  border-radius: 8px;
  padding: 48px;
  border: 1px solid #e4e7ed;
  max-width: 500px;
  margin: 0 auto;
}

/* 确保子组件样式适配 */
:deep(.section-container),
:deep(.form-container) {
  background: transparent;
  box-shadow: none;
  border: none;
}

:deep(.page-header) {
  margin-bottom: 0;
  background: transparent;
  padding: 0;
  box-shadow: none;
}
</style> 